//
//  OptionView.m
//  Foundation
//
//  Created by 新庭 on 2019/5/20.
//

#import "OptionView.h"
#import "OptionItem.h"
#import <Masonry/Masonry.h>

@interface OptionView ()

@property (nonatomic, strong) UISelectionFeedbackGenerator *selectionFeedback API_AVAILABLE(ios(10.0));

@end

@implementation OptionView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
    }
    return self;
}

+ (instancetype)optionViewWith:(NSArray *)items {
    OptionView *optionView = [[self alloc] init];
    optionView.items = [items jk_map:^id(id object) {
        if ([object isKindOfClass:OptionItem.class]) {
            return object;
        }
        return [OptionItem itemWith:object];
    }];
    return optionView;
}

- (void)setSelectedIndex:(NSUInteger)selectedIndex {
    _selectedIndex = selectedIndex;
    
    if (@available(iOS 10.0, *)) {
        [self.selectionFeedback selectionChanged];
    } else {
    }
    [self sendActionsForControlEvents:UIControlEventValueChanged];
}

- (void)setItems:(NSArray<OptionItem *> *)items {
    _items = items;
}

- (OptionItem *)selectedItem {
    return self.items[self.selectedIndex];
}

- (NSString *)stringForItem:(OptionItem *)item {
    if (self.titleFormater) {
        return self.titleFormater(item);
    }
    return ((NSObject *)item.item).description;
}

#pragma mark - Private
- (UISelectionFeedbackGenerator *)selectionFeedback {
    if (!_selectionFeedback) {
        _selectionFeedback = [[UISelectionFeedbackGenerator alloc] init];
        [_selectionFeedback prepare];
    }
    return _selectionFeedback;
}

@end
